package com.mdd.admin.service.comment.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.mdd.admin.service.comment.IGoodsCommentService;
import com.mdd.admin.service.image.IGoodsCommentImageService;
import com.mdd.admin.validate.comment.GoodsCommentPageParam;
import com.mdd.admin.validate.comment.GoodsCommentParam;
import com.mdd.admin.validate.comment.GoodsCommentReplyParam;
import com.mdd.admin.vo.comment.GoodsCommentDetailVo;
import com.mdd.admin.vo.comment.GoodsCommentListVo;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.dto.GoodsCommentPageDto;
import com.mdd.common.dto.result.GoodsCommentPageResultDto;
import com.mdd.common.entity.goods.GoodsComment;
import com.mdd.common.entity.image.GoodsCommentImage;
import com.mdd.common.enums.GoodsCommentLevelEnum;
import com.mdd.common.enums.GoodsCommentStatusEnum;
import com.mdd.common.mapper.comment.GoodsCommentMapper;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务评价实现类
 */
@Service
public class GoodsCommentServiceImpl implements IGoodsCommentService {

    @Resource
    GoodsCommentMapper goodsCommentMapper;

    @Resource
    private IGoodsCommentImageService commentImageService;

    /**
     * 服务评价列表
     *
     * @param params 搜索参数
     * @return PageResult<GoodsCommentListVo>
     */
    @Override
    public PageResult<GoodsCommentListVo> list(GoodsCommentPageParam params) {
        Page<GoodsCommentListVo> page = new Page<>(params.getPageNo(), params.getPageSize());
        GoodsCommentPageDto pageDto = new GoodsCommentPageDto();
        if (StringUtils.isNotEmpty(params.getStartTime())) {
            pageDto.setStartTime(TimeUtil.dateToTimestamp(params.getStartTime()));
        }
        if (StringUtils.isNotEmpty(params.getEndTime())) {
            pageDto.setEndTime(TimeUtil.dateToTimestamp(params.getEndTime()));
        }
        BeanUtils.copyProperties(params, pageDto);
        Page<GoodsCommentPageResultDto> resultDtoPage = goodsCommentMapper.pageResult(page, pageDto);
        if (resultDtoPage == null || CollectionUtils.isEmpty(resultDtoPage.getRecords())) {
            return PageResult.iPageHandle(0L, page.getCurrent(), page.getSize(), Lists.newArrayList());
        }
        List<GoodsCommentPageResultDto> records = resultDtoPage.getRecords();
        List<Long> commentIds = records.stream().map(GoodsCommentPageResultDto::getId).collect(Collectors.toList());
        List<GoodsCommentImage> commentImageList = commentImageService.listByCommentIds(commentIds);
        Map<Long, List<GoodsCommentImage>> commentImageMap = commentImageList.stream().collect(Collectors.groupingBy(GoodsCommentImage::getCommentId));
        List<GoodsCommentListVo> list = new LinkedList<>();
        // 数据转换
        for (GoodsCommentPageResultDto item : records) {
            GoodsCommentListVo vo = new GoodsCommentListVo();
            vo.setId(item.getId());
            vo.setGoodsId(item.getGoodsId());
            vo.setUserId(item.getUserId());
            vo.setOrderGoodsId(item.getOrderGoodsId());
            vo.setServiceComment(item.getServiceComment());
            vo.setComment(item.getComment());
            vo.setReply(item.getReply());
            vo.setStatus(item.getStatus());
            vo.setStatusName(GoodsCommentStatusEnum.getMap().get(vo.getStatus()));
            vo.setCommentLevel(item.getCommentLevel());
            vo.setCommentLevelName(GoodsCommentLevelEnum.getMap().get(vo.getCommentLevel()));
            if (commentImageMap.containsKey(item.getId())) {
                List<GoodsCommentImage> imageList = commentImageMap.get(item.getId());
                List<String> commentImageUrlList = Lists.newArrayList();
                for (GoodsCommentImage commentImage : imageList) {
                    commentImageUrlList.add(UrlUtil.toAbsoluteUrl(commentImage.getUri()));
                }
                vo.setCommentUrlList(commentImageUrlList);
            }
            vo.setAvatarUrl(UrlUtil.toAbsoluteUrl(item.getAvatarUri()));
            vo.setNickname(item.getNickname());
            vo.setUsername(item.getUsername());
            vo.setSn(item.getSn());
            vo.setGoodsImageUrl(UrlUtil.toAbsoluteUrl(item.getGoodsImageUri()));
            vo.setGoodsName(item.getGoodsName());
            vo.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }
        return PageResult.iPageHandle(page.getTotal(), page.getCurrent(), page.getSize(), list);
    }

    /**
     * 服务评价详情
     *
     * @param id 主键参数
     * @return GoodsComment
     */
    @Override
    public GoodsCommentDetailVo detail(Integer id) {
        GoodsComment model = goodsCommentMapper.selectOne(
                new QueryWrapper<GoodsComment>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        GoodsCommentDetailVo vo = new GoodsCommentDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 服务评价新增
     *
     * @param goodsCommentParam 参数
     */
    @Override
    public void add(GoodsCommentParam goodsCommentParam) {
        GoodsComment model = new GoodsComment();
        model.setGoodsId(goodsCommentParam.getGoodsId());
        model.setUserId(goodsCommentParam.getUserId());
        model.setOrderGoodsId(goodsCommentParam.getOrderGoodsId());
        model.setServiceComment(goodsCommentParam.getServiceComment());
        model.setComment(goodsCommentParam.getComment());
        model.setReply(goodsCommentParam.getReply());
        model.setStatus(goodsCommentParam.getStatus());
        model.setCreateTime(TimeUtil.timestamp());
        model.setUpdateTime(TimeUtil.timestamp());
        goodsCommentMapper.insert(model);
    }

    /**
     * 服务评价编辑
     *
     * @param goodsCommentParam 参数
     */
    @Override
    public void edit(GoodsCommentParam goodsCommentParam) {
        GoodsComment model = goodsCommentMapper.selectOne(
                new QueryWrapper<GoodsComment>()
                        .eq("id", goodsCommentParam.getId())
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        model.setId(goodsCommentParam.getId());
        model.setReply(goodsCommentParam.getReply());
        model.setStatus(GoodsCommentStatusEnum.REPLY.getStatus());
        model.setUpdateTime(TimeUtil.timestamp());
        goodsCommentMapper.updateById(model);
    }

    /**
     * 服务评价删除
     *
     * @param id 主键ID
     */
    @Override
    public void del(Long id) {
        GoodsComment model = goodsCommentMapper.selectOne(
                new QueryWrapper<GoodsComment>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        model.setDeleteTime(TimeUtil.timestamp());
        model.setIsDelete(GlobalConstant.DELETE);
        goodsCommentMapper.updateById(model);
    }


    @Override
    public void replyComment(GoodsCommentReplyParam params) {
        GoodsComment model = goodsCommentMapper.selectOne(
                new QueryWrapper<GoodsComment>()
                        .eq("id", params.getId())
                        .last("limit 1"));
        Assert.notNull(model, "数据不存在!");
        model.setReply(params.getContent());
        model.setStatus(GoodsCommentStatusEnum.REPLY.getStatus());
        model.setUpdateTime(TimeUtil.timestamp());
        goodsCommentMapper.updateById(model);
    }

}
